moment.lang("it");

getUpdateTime = function(){
return  moment().startOf('hour').fromNow();
}

var MAP = {
  lat : null,
  lng : null,
  map : null,
  bounds : null,
  markerGroup : null,
  markersClustered : null,
  markersGeoJson : [],

  markers :{
 
  },
  
  traipler : {
    coords : null,
  },
  
  init : function (){
  
    MAP.lat = jQuery("#mappa").data("lat");
    MAP.lng = jQuery("#mappa").data("lng");
    
   // var style_array_from_above_here = [{"featureType":"water","stylers":[{"color":"#46bcec"},{"visibility":"on"}]},{"featureType":"landscape","stylers":[{"color":"#f2f2f2"}]},{"featureType":"road","stylers":[{"saturation":-100},{"lightness":45}]},{"featureType":"road.highway","stylers":[{"visibility":"simplified"}]},{"featureType":"road.arterial","elementType":"labels.icon","stylers":[{"visibility":"off"}]},{"featureType":"administrative","elementType":"labels.text.fill","stylers":[{"color":"#444444"}]},{"featureType":"transit","stylers":[{"visibility":"off"}]},{"featureType":"poi","stylers":[{"visibility":"off"}]}]
    
    MAP.map = new GMaps({
      div: '#mappa',
      //styles: style_array_from_above_here,
      lat:  MAP.lat,
      lng:   MAP.lng
     
    });
  
    
    setTimeout(function(e){
       MAP.map.addMarker({
           lat:  MAP.lat,
           lng:  MAP.lng,
           title: jQuery(".post_title").text(),
          // icon: 'images/beachflag.png',
           animation: google.maps.Animation.DROP,
           infoWindow: {
             content: '<p>'+jQuery(".post_title").text()+'</p>'
           },
           click: function(e) {
            // alert(jQuery(".post_title").text());
           }
         });
      },1000)
  
    
    
    
    jQuery(".icon-compass").on("click",function(e){
      
      //if(confirm("Aprire Google Maps per le seguire le indicazioni?")){
        
        var url = "http://maps.google.com/?&daddr="+MAP.lat+","+ MAP.lng;
        window.open(
          url,
          '_blank' // <- This is what makes it open in a new window.
        );

  })

    
  },
  
  serviceClicked : function(e){
    
    var type =  jQuery(this).toggleClass('active').data("service");
    console.log(type)
    if(jQuery(this).hasClass('active')){
      jQuery(this).find('input').prop('checked',true);
      MAP.switchService(type);
      
    }else{
      jQuery(this).find('input').prop('checked',false);
      MAP.removeMarkersByType(type)
    }
    
    return false;
    
  },
  
  
  switchService : function(service){
      var point;
          
      switch(service){
              
              case "bike":
                point = bike;
                currColor = "d30000";
              break;
              
              case "train":
                point = train;
                currColor = "00F8F0";
              break;
              
              case "traffic":
                point = traffic;
                currColor = "71ae26";
              break;
              
              case "events":
                point = events;
                currColor = "d300FF";
              break;
              
              case "bus":
                point = bus;
                currColor = "d300FF";
              break;
                
              default:
                point = bike;
                currColor = "d300FF";
                service = "bike";
              break;
              
      }
      
      
    // jQuery("li[data-service="+service+"] .icon_service ").css("background",currColor ) ;
      MAP.addMarkersByType(point,service);
 
 
  },
  
  
  createTraiplerMarker : function(){
    var title = "TRAIPLER";
    var description = "DESCRIPTION";
    
    var marker = L.marker(MAP.traipler.coords, {
        icon: L.AwesomeMarkers.icon({
          prefix: 'icon',
          icon: "traipler",
          markerColor: "traipler"
        }),
        
        description: description,
        type : "traipler",
        title: title
    })
    //.addTo(MAP.map);
    
  
    marker.bindPopup(
       MAP.getMarkerPopupByType(
       {
        title : "ROIALTO" 
       },"traipler"),
       
       {
        autoPanPaddingBottomRight : L.point(250,10)
       }
    );
    
    
    return marker;
  },
  
  
  removeMarkersByType : function(type){
    
    try{
      MAP.markersClustered.removeLayers( MAP.markers[type])
    }catch(e){
      
    }
    
    setTimeout(function() {
        MAP.map.fitBounds(MAP.markersClustered.getBounds());
        //MAP.map.fitBounds(MAP.map.getBounds());
    }, 200)
    
    
  },
  
  addMarkersByType: function(point,type) {
      
      MAP.initMarkersCluster(type);
      
      /*CLICA CREAZIONE MARKERS*/
      // jQuery.each(storesArray, function(i, store) {
      
      //     //Build Markers List
      //     MAP.markersClustered.addLayer(MAP.createSingleClusterMarker(store));
          
      // });
      
      /*var colors = ["d30000","00F8F0","F88D00"];
      var currColor = colors[Math.floor(colors.length * Math.random())];*/
      
      var markersArr = [];
      
      for (var i = 0; i < point.length; i++) {
        var newMarker = MAP.createSingleClusterMarker(point[i],type,i,currColor);
        //MAP.markersClustered.addLayer(newMarker);
        
        markersArr.push(newMarker)
        //MAP.markersClustered.addLayer(MAP.createSingleClusterMarker(point[i],type,i,currColor));
       // MAP.markersClustered.addLayer(MAP.createSingleClusterMarker(point[i],type,i,currColor));
      }
      
      MAP.markers[type] = markersArr;
      MAP.markersClustered.removeLayers( MAP.markers[type])
      
      MAP.markersClustered.addLayers( MAP.markers[type])
      
      MAP.map.addLayer(MAP.markersClustered);
      
      
      setTimeout(function() {
          MAP.map.fitBounds(MAP.markersClustered.getBounds());
          //MAP.map.fitBounds(MAP.map.getBounds());
      }, 200)
      
    
       
  },
  
  createSingleClusterMarker : function(point,type,i,currColor){
    
    var title = point.title + " - " + i;
    var description = point.description+ " - " + i;
    
    var coords = MAP.getRandomCoords();
    
    if(point.coords){
      coords=point.coords
    }
    
    var marker = L.marker(coords, {
        
        icon: MAP.getMarkerIconByType(type,currColor),
        
        identifier: point,
        description: description,
        type : type,
        title: title
    });
    
    
    var _minWidth = 300;
    if(type=="train" )
      _minWidth = 600;
    
    marker.bindPopup(
                     MAP.getMarkerPopupByType(point,type),
                     {
                      autoPanPaddingBottomRight : L.point(250,10),
                      minWidth: _minWidth,
                      maxHeight : 300
                     }
                     );
    
    return marker;
  },
  
  
  getMarkerPopupByType : function (point,type){
      
      var tmpl = "#"+type+"Tmpl";
  
      var html = Mustache.to_html(jQuery(tmpl).html(), point);
      return html;
  },
  
  
  getMarkerIconByType : function (type,currColor){
    
   
   
    
    var icon = L.mapbox.marker.icon({
                'marker-type': 'Point',
                'marker-size': 'medium',
                'marker-color': currColor
            })
    
    icon = L.divIcon({
                // specify a class name that we can refer to in styles, as we
                // do above.
                className: 'marker-'+type,
                // html here defines what goes in the div created for each marker
                //html: i,
                // and the marker width and height
                iconSize: [40, 40]
            })
    
    // Creates a red marker with the coffee icon
      icon = L.AwesomeMarkers.icon({
        prefix: 'icon-e015',
        icon: type,
        markerColor: type
      });


    
    return icon;
    
    
  },
  
  clusterClicked: function(cluster) {
      var childrens = cluster.layer.getAllChildMarkers();
      console.log(childrens)
     // MAP.hideAllMarkers();
      
      jQuery.each(childrens, function(index, marker) {
          var markerID = marker.options.identifier;
          //MAP.scrollToMarkerBox(markerID)
          
          //MAP.hightlightMarker(markerID,true);
      });
      
      MAP.closeSlidePanel(".post_contacts");
     
  },
  
  
  getRandomCoords : function(bounds) {
    bounds = MAP.bounds;
       var lat_min = bounds.getSouthWest().lat,
           lat_range = bounds.getNorthEast().lat - lat_min,
           lng_min = bounds.getSouthWest().lng,
           lng_range = bounds.getNorthEast().lng - lng_min;
           
           var LatLng = new L.latLng(lat_min + (Math.random() * lat_range),lng_min + (Math.random() * lng_range));
       //return [lat_min + (Math.random() * lat_range), lng_min + (Math.random() * lng_range)];
       return LatLng;
  },

  
  markerClicked: function(markerID) {
      if (markerID) {
          //MAP.hightlightMarker(markerID);
          //MAP.scrollToMarkerBox(markerID)
      }
      MAP.closeSlidePanel(".post_contacts");

  },
  
  initMarkersCluster : function (type){
    
    //INIT FIRST TIME MARKERCLUSTER
      if(MAP.markersClustered===null){
        
        
        MAP.markersClustered = new L.MarkerClusterGroup({
            //removeOutsideVisibleBounds : 1,
             animateAddingMarkers: true ,
            showCoverageOnHover: 0,
            iconCreateFunction: MAP.markerClusterIconCreateFunction(type)
        });
        
        
        /*CLICK ON SINGLE MARKER*/
        MAP.markersClustered.on("click", function(marker) {
            //console.log(marker)
            MAP.markerClicked(marker.layer.options.identifier);
        })
        
        /*CLICK ON CLUSTER*/
        MAP.markersClustered.on("clusterclick", function(cluster) {
          MAP.clusterClicked(cluster);
        })
        
        
      }else{
        
        MAP.markersClustered.options.iconCreateFunction = MAP.markerClusterIconCreateFunction(type)
   
        
      }
    
      //Reset Marker Cluster
     /* MAP.markersGeoJson = [];
      try {
          MAP.markerGroup.clearLayers();
          MAP.map.removeLayer(MAP.markerGroup)
          MAP.markersClustered.clearLayers();
          MAP.map.removeLayer(MAP.markersClustered)
      } catch (e) {}*/
      
  },
  
  markerClusterIconCreateFunction : function (type){
    return function(cluster) {
                var childCount = cluster.getChildCount();
                var c = ' marker-cluster-';
                if (childCount < 10) {
                    c += 'small';
                } else if (childCount < 100) {
                    c += 'medium';
                } else {
                    c += 'large';
                }
                
                c += " "+type;
                return new L.DivIcon({
                    html: '<div class="corner '+type+'"><span>' + childCount + '</span></div>',
                    className: 'marker-cluster' + c,
                    iconSize: new L.Point(40, 40)
                });
            }
  },
  
  toggleSlidePanel : function(){
    jQuery(this).parent(".slidePanel").toggleClass('closed');
     // jQuery(".post_contacts").toggleClass('closed');
  },
  
  closeSlidePanel : function (el){
    jQuery(el).addClass('closed')
    
  },
  
  openSlidePanel : function (el){
    jQuery(el).removeClass('closed')
    
  },
  
  locate: function(){
    MAP.map.locate();
    
    // Once we've got a position, zoom and center the map
    // on it, and add a single marker.
    MAP.map.on('locationfound', function(e) {
      
      var currPosition = e.latlng,
          from = [currPosition.lat,currPosition.lng];
     
       // MAP.map.fitBounds(e.bounds);

        MAP.map.featureLayer.setGeoJSON({
            type: "Feature",
            geometry: {
                type: "Point",
                coordinates: [e.latlng.lng, e.latlng.lat]
            },
            properties: {
                'marker-color': '#000',
                'marker-symbol': 'star-stroked'
            }
        });
        
        
        MAP.getDirections(currPosition,MAP.traipler.coords);

    });
    
  },
  
  
  geocoder : function(){
    var geocoder = L.mapbox.geocoder(MAP.mapboxId);
    
    geocoder.query("Italy",function(err,result){
      console.log(result)
    })
    
  },
  
  getDirections : function(from, to){
     
      //var coords = "12.464721,41.905107;12.45798110961914,41.90898435055055";
      var coords = from.lng+","+from.lat+";"+ to.lng+","+to.lat;
      
      jQuery.getJSON('http://api.tiles.mapbox.com/v3/examples.map-9ijuk24y/directions/driving/'+coords+'.json', 
          {param1: 'value1'}, 
          
          function(directions, textStatus) {
            console.log(directions, textStatus);
            if(directions.routes){
              var route = directions.routes[0].geometry
              MAP.drawDirections(route);
            }else{
              alert("Nessun itinerario trovato")
            }
          }
      );
  },
  
  drawDirections : function(directions){
 
    var myStyle = {
        "color": "#ff7800",
        "weight": 5,
        "opacity": 0.65
    };

    var route = L.geoJson(directions, {
        style: myStyle
    })
    route.addTo(MAP.map);
    
    
    //SET BOUNDS
    var first = [directions.coordinates[0][1], directions.coordinates[0][0]],
        last = [directions.coordinates[directions.coordinates.length-1][1], directions.coordinates[directions.coordinates.length-1][0]];
    
    MAP.map.fitBounds([first,last]);
   
   MAP.closeSlidePanel(".post_contacts");
  }
  
};




var player;
var isPaused=false;

jQuery(document).ready(function($) {
  
  
  
  //VIDEO PLAYER
 // if (navigator.userAgent.match(/(iPod|iPhone|iPad)/))
  //$("#container").css("margin-top","55px");

    initPlayer();

    $(".post_thumb,.ico_play").on("click",function(){
        playVideo();
    });
   //$(".post_content").fitVids();
   $(".fluid-width-video-wrapper").css("padding-top","35%");
   $("iframe.vimeo").addClass('closed');


   //$(".blackOverlay").on("click mouseover mousemove",stopVideo);


   //SOCIALS
    /*$(".post_socials .social_ico").on("click",function(){
        window.open(
          $(this).attr("href"),
          '_blank' // <- This is what makes it open in a new window.
        );
    });*/
    
    $(".embed_ico").click(function() {
        $(".embedcode").slideToggle("fast", function() {
            $(".embedcode textarea").focus(function() {
                $(this).select();
            }).focus();
        });
    })


  MAP.init();
    
  setTimeout(playVideo,500)
  //initMisiedo()
});//end ready


function playVideo(){
  isPaused=false;
   jQuery(".post_thumb").fadeOut();
   //jQuery(".social_flags").fadeOut();
   jQuery(".fluid-width-video-wrapper").animate({"padding-top":"56%"});
   jQuery("iframe.vimeo")
   .css({"height":"500px"})
   .removeClass('closed')





   if( ! /mobi/i.test(navigator.userAgent)){
     jQuery("#traipler_topbar").css("top","-80px");
    // jQuery(".blackOverlay").fadeIn();
     jQuery("#feedbackWidget").css("left","-340px");



      player.api('play');

      //FULLSCREEN
      /*if (RunPrefixMethod(document, "FullScreen") || RunPrefixMethod(document, "IsFullScreen")) {
                 RunPrefixMethod(document, "CancelFullScreen");
               }
               else {
                 RunPrefixMethod(this, "RequestFullScreen");
               }

*/

  }else{

  }

}



function pauseVideo(){
    isPaused=true;
     player.api('pause');
     stopVideo()
}


function stopVideo(e){


  if(isPaused || e.type=="click"){
      player.api('pause');
      isPaused=false;



      jQuery(".fluid-width-video-wrapper").animate({"padding-top":"35%"});
      jQuery("iframe.vimeo").css({"height":""}).addClass("closed")
      jQuery(".social_flags").fadeIn();
      //.animate({"height":"500px"});

      if( ! /mobi/i.test(navigator.userAgent)){
        //jQuery(".post_thumb").fadeIn();
        jQuery(".blackOverlay").fadeOut();
        jQuery("#feedbackWidget").css("left","-300px");
        jQuery("#traipler_topbar").css("top","0px");
      }

   }
}


function initPlayer(){
    var iframe = jQuery('#vimeo0')[0];
    player = $f(iframe),

    // When the player is ready, add listeners for pause, finish, and playProgress
    player.addEvent('ready', function() {
        // player.api('play');
        player.addEvent('play', playVideo);
        player.addEvent('pause', pauseVideo);
        player.addEvent('finish', onFinishVideo);
       // player.addEvent('playProgress', onPlayProgress);
    });

}

function onFinishVideo(id) {
    console.log('finished');
}

function onPlayProgress(data, id) {
    console.log(data.seconds + 's played');
}

/*
function initMisiedo(){
  
  if(jQuery('#mswidget').length>0){
    
    var misiedo_code = parseInt(jQuery('#mswidget').data("misiedo"));
    console.log(misiedo_code)
    window.onload = function() {
        loadMSScript({
            height: '250',
            width: '1000',
            url: 'http://misiedo.com',
            aid: 68657, 
            rid: misiedo_code,
            version: 2
            });
        };
  }
 
}*/

var pfx = ["webkit", "moz", "ms", "o", ""];
function RunPrefixMethod(obj, method) {

  var p = 0, m, t;
  while (p < pfx.length && !obj[m]) {
    m = method;
    if (pfx[p] === "") {
      m = m.substr(0,1).toLowerCase() + m.substr(1);
    }
    m = pfx[p] + m;
    t = typeof obj[m];
    if (t != "undefined") {
      pfx = [pfx[p]];
      return (t == "function" ? obj[m]() : obj[m]);
    }
    p++;
  }

}






